﻿#region Imports
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CommonUtilities.Commands;
using CommonUtilities.Extensions;
using PlayRandom.ViewModels;
#endregion Imports

namespace PlayRandom.Views
{
    /// <summary>
    /// Interaction logic for TimestampSelector.xaml
    /// </summary>
    public partial class TimestampSelector : Window
    {
        #region Declarations
        MainViewModel viewModel = null;
        #endregion Declarations

        #region Constructors
        private TimestampSelector()
        {
            InitializeComponent();
            chkSortTimestamp_Checked(null, null);

            btnSaveTimestamp.IsDefault = true;
            btnCloseTimestamp.IsCancel = true;

            lstTimestamp.Items.Clear();
        }

        public TimestampSelector(MainViewModel dataContext, SizeToContent sizeToContent)
            : this()
        {
            this.SizeToContent = sizeToContent = SizeToContent.WidthAndHeight;
            this.MinWidth = this.MaxWidth = this.Width = (120 - (dataContext.IsUpdateMode ? 0 : 10)) * Convert.ToInt32(this.FindResource("UnigridColumnCount"));

            dataContext.CloseTimestampWindowCommand = new RelayCommand((parameter) => btnClose_Click());
            dataContext.bkpTimestamp = dataContext.SelectedFavFile.Timestamps.ToObservableCollection();
            dataContext.IsSortAsc = EvaluateTimestampSort(dataContext.SelectedFavFile.Timestamps);
            this.DataContext = viewModel = dataContext;
        }

        private bool? EvaluateTimestampSort(ObservableCollection<string> timestamps)
        {
            var vm = this.DataContext as MainViewModel;

            if (timestamps.AppendText("|") == timestamps.OrderBy(ts => ts).AppendText("|")) return true;
            else if (timestamps.AppendText("|") == timestamps.OrderByDescending(ts => ts).AppendText("|")) return false;
            else return null;
        }
        #endregion Constructors

        #region Events
        private void btnClose_Click()
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                if (viewModel.IsDirty && viewModel.IsUpdateMode)
                {
                    if (MessageBox.Show("Close without saving?\r\nSelect YES to revert changes or NO to continue editing..", "Confirmation..", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        viewModel.SelectedFavFile.Timestamps = viewModel.timestampBeforeUpdate.Split(MainViewModel.DELIM_TIMESTAMP_INI).ToObservableCollection();
                        e.Cancel = false;
                    }
                    else e.Cancel = true;
                }
                else if (!viewModel.IsUpdateMode) viewModel.SelectedFavFile.Timestamps = viewModel.bkpTimestamp.ToObservableCollection();
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }

        private void lstTimestamp_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                lstTimestamp.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Escape: this.Close(); break;
                default: break;
            }
        }

        private void chkSortTimestamp_Checked(object sender, RoutedEventArgs e)
        {
            if (!chkSortTimestamp.IsChecked.HasValue)
            {
                chkSortTimestamp.Content = "■";
                chkSortTimestamp.ToolTip = "Default";
            }
            else
            {
                switch (chkSortTimestamp.IsChecked.Value)
                {
                    case true:
                        chkSortTimestamp.Content = "▲";
                        chkSortTimestamp.ToolTip = "Ascending";
                        break;

                    case false:
                        chkSortTimestamp.Content = "▼";
                        chkSortTimestamp.ToolTip = "Descending";
                        break;
                }
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            (this.DataContext as MainViewModel).IsTimestampSelectorOpen = false;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            (this.DataContext as MainViewModel).IsTimestampSelectorOpen = true; // only when ready
        }
        #endregion Events

        #region ILogger members
        public void LogError(Exception ex)
        {
            viewModel.LogError(ex);
        }
        #endregion ILogger members
    }
}
